import axios,{ type AxiosRequestConfig,type AxiosError,type InternalAxiosRequestConfig } from "axios";
const instance=axios.create({
  timeout:2000
})
instance.interceptors.request.use(
  (config:InternalAxiosRequestConfig)=>{
    config.headers.set('Content-Type','application/json')
    if(config.method == 'post'){
      config.data=JSON.stringify(config.data)
    }
    return config
  },
  (error:AxiosError)=>{
    Promise.reject(error)
  }
)
instance.interceptors.response.use(
  (response)=>{
    return response.status == 200 ? Promise.resolve(response) : Promise.reject(response)
  },
  (error)=>{
    const { response }=error
    errorHanld(response.status,response.info)
  }
)
const errorHanld=(status:number,info:string)=>{
  switch (status) {
    case 400:
    console.log('语义有误');
      break;
    case 401:
    console.log('服务器认证');
    window.location.href='/LoginView'
      break;
    case 402:
    console.log('服务器拒绝访问');
      break;
    case 403:
    console.log('地址有误');
      break;
    case 500:
    console.log('服务器遇到意外');
      break;
    case 502:
    console.log('服务器无响应');
      break;
    default:
      console.log(info);
      break;
  }
}
export default instance
